<?php

class Application_Model_PageMapper {

  protected $_dbTable;

  public function setDbTable($dbTable) {
    if(is_string($dbTable)){
      $dbTable = new $dbTable();
    }
    if(!$dbTable instanceof Zend_Db_Table_Abstract){
      throw new Exception('Invalid table data gateway provider');
    }
    $this->_dbTable = $dbTable;
    return $this;
  }
  
  public function getDbTable(){
    if(null === $this->_dbTable){
      $this->setDbTable('Application_Model_DbTable_Page');
    }
    return $this->_dbTable;
  }
  
  public function save(Application_Model_Page $page){
    
    $data = array(
        'uri' => $page->getUri(),
        'full_uri' => $page->getFull_uri()
    );
            
    if(null === ($id = $page->getId())){
      unset($data['id']);
      $this->getDbTable()->insert($data);
    } else {
      $this->getDbTable()->update($data, array('id = ?' => $id));
    }
    
  }
  
  public function find($id, Application_Model_Page $page){
    $result = $this->_dbTable()->find($id);
    if(0 == count($result)){
      return;
    }
    $row = $result->current();
    $page->setId($row->id)
         ->setUri($row->uri)
         ->setFullUri($row->full_uri);
  }
  
  public function fetchAll(){
    $resultSet = $this->getDbTable()->fetchAll();
    $entries = array();
    foreach ($resultSet as $row){
      $entry = new Application_Model_Page();
      $entry->setId($row->id)
            ->setUri($row->uri)
            ->setFull_uri($row->full_uri);
      $entries[] = $entry;
    }
    return $entries;
  }

}

